package com.article.lock;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.exception.ZkException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 将等待锁的用户比较排序，查看本身是否为第一个用户，避免羊群效应
 */
public class ZookeeperImproveLock extends ZookeeperAbstractLock {
    private static final Logger log = LoggerFactory.getLogger(ZookeeperDistributeLock.class);

    private String beforePath;//前一个节点
    private String currentPath;//当前节点
    private CountDownLatch cdl = null;

    public ZookeeperImproveLock() {
        if (!this.zkClient.exists(path)) {
            this.zkClient.createPersistent(path, "lock");
        }
    }

    @Override
    public void waitForLock() {
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("===================================");
                if (cdl != null) {
                    cdl.countDown();
                }
            }

            @Override
            public void handleDataChange(String dataPath, Object o) throws Exception {

            }
        };
        zkClient.subscribeDataChanges(beforePath, listener);
        if (zkClient.exists(beforePath)) {
            cdl = new CountDownLatch(1);
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        zkClient.unsubscribeDataChanges(beforePath, listener);
    }

    @Override
    public boolean tryLock() {
        if (currentPath == null || currentPath.length() <= 0) {
            currentPath = this.zkClient.createEphemeralSequential(path + '/', "lock");
        }
        List<String> childrens = this.zkClient.getChildren(path);
        Collections.sort(childrens);
        if (currentPath.equals(path + '/' + childrens.get(0))) {
            return true;
        } else {
            int wz = Collections.binarySearch(childrens, currentPath.substring(6));
            beforePath = path + '/' + childrens.get(wz - 1);
        }
        return false;
    }
}
